﻿
package com.ostrich.manpower.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.base.service.BaseService;
import com.base.util.DateUtil;
import com.base.util.SessionUtils;
import com.ostrich.manpower.bean.TostHrBaseinfo;
import com.ostrich.manpower.bean.TostHrCheckinlog;
import com.ostrich.system.bean.TostSysParaminfo;
import com.ostrich.manpower.common.FormulaUtil;
import com.ostrich.manpower.common.ImportUtil;
import com.ostrich.manpower.common.StringUtils;
import com.ostrich.manpower.service.TostHrCheckinlogDao;
import com.ostrich.system.analysis.ParaminfoUtil;
/**
 * @author wangyinan
 * @brief    模块功能简单描述
 * @details  模块功能详细描述
 */
@Service("tostHrCheckinlogService")
public class TostHrCheckinlogService<T> extends BaseService<T> {
	private final static Logger log= Logger.getLogger(TostHrCheckinlogService.class);

	@Autowired(required=false)
    private TostHrCheckinlogDao<T> dao;
	@Autowired(required=false)
	TostHrCheckinlogService<TostHrCheckinlog> tostHrCheckinlogService;

	public TostHrCheckinlogDao<T> getDao() {
		return dao;
	}
	
	@Autowired(required=false)
	TostHrBaseinfoService<TostHrBaseinfo> tosthrbaseinfoservice;
	
	public List<T> queryCheckInLogByHrId(int hrId){
		return dao.queryCheck(hrId);
	}
	
	//差算法
	public void addCheck(TostHrCheckinlog tcl){
	
		dao.addCheck(tcl);
	}
	//差算法
	public void updateCheck(TostHrCheckinlog tcl){
		
		dao.updateCheck(tcl);
	}
	
	 //导入
	public String checklogBySheet(String month,HSSFSheet sheet,HttpServletRequest request) throws Exception{
		HSSFRow row=null;
		int colnum=6;
		String msg ="";
		Map<String,TostSysParaminfo> typename = ParaminfoUtil.getParamKeyNameByPid(50);
		System.out.println(sheet.getPhysicalNumberOfRows()+"^^^^^^^^^^^^^^^");
		for(int j=2;j<sheet.getPhysicalNumberOfRows();j++){
			row=sheet.getRow(j);
			//先匹配个人编号
			String iscontinut = (row!=null)?ImportUtil.getCellValue(row.getCell(1)):null;
       	 	TostHrBaseinfo bsinfo= (TostHrBaseinfo) tosthrbaseinfoservice.getBaseinfoByHrCode(iscontinut);
			TostHrCheckinlog tcl=new TostHrCheckinlog();
			if(iscontinut!=null){
				if(bsinfo==null||bsinfo.getId() == null){
					msg +="第"+(j+1)+"行记录异常：工号："+iscontinut+"，姓名为："+ImportUtil.getCellValue(row.getCell(2))+"的考勤没有正常导入（工号不存在）。";
					continue;
				}
			}
			if(iscontinut!=null && iscontinut.length()>0 && (ImportUtil.getCellValue(row.getCell(2))).equalsIgnoreCase(bsinfo.getHrName()) ){
				for(int i=0;i<colnum;i++){
					String str=ImportUtil.getCellValue(row.getCell(i));
					TostSysParaminfo tpr = new TostSysParaminfo();
					if(i==3)//得到对应的type类型 eg:迟到,病假
						tpr=typename.get(str);
					else if(i==4)
						str=(StringUtils.isNum(str))?str:"0";
					switch(i){
						//case 0:String hrname=str;tcl.setHrName(hrname);tcl.setHrId(bsinfo.getId());break;
						case 3:tcl.setHciType(tpr.getPaValue());break;
						case 4:tcl.setHciDaynum(Float.parseFloat(str));break;
					}
				    if(i==5){
				      Float flstr = (str!=null  && str.trim().length()>0 && str.matches("^[0-9]+\\.{0,1}[0-9]{0,2}$"))?Float.parseFloat(str):new Float(0);
					  tcl.setHciDeductionsTotal(flstr);
				      }
				}
				tcl.setHciMonth(month);
				if(tcl!=null && bsinfo!=null && bsinfo.getHrName()!=null ){
					tcl.setHrId(bsinfo.getId());
					tcl.setHrName(bsinfo.getHrName());
					//查询改用的该类型该月份 有数据
					TostHrCheckinlog cklg= queryChenckLog(tcl);
					if(cklg!=null && cklg.getId()!=null){
						tcl.setId(cklg.getId());
						updateCheck(tcl);
					}else{
						tcl.setCreatetime(DateUtil.getNowPlusTime());
						tcl.setPerson(SessionUtils.getUser(request).getEmail());
						addCheck(tcl);
					}
				}
			 }else{
				 msg +="第"+(j+1)+"行记录异常：工号："+iscontinut+"，姓名为："+ImportUtil.getCellValue(row.getCell(2))+"的考勤没有正常导入（工号跟姓名不匹配）。";
	       	 	continue;
			 }
		}
		return msg;
	}
	/****通过获取它的类型 返回是否扣款或者补贴数据的总和。
	 *  超短代码没有用
	 * @param tcl
	 * @return
	 */
	public Float totle(TostHrCheckinlog tcl) {
		Float totle = new Float(0);
		TostHrBaseinfo bsinfo = tosthrbaseinfoservice.queryById(tcl.getHrId());
		// 计算扣款和补贴的合计值
		Float exealry = (bsinfo != null && bsinfo.getHrExesalry() != null) ? bsinfo
				.getHrExesalry() : new Float(0);
//		Float leavemy = (bsinfo != null && bsinfo.getHrLeavemoney() != null) ? bsinfo
//				.getHrLeavemoney() : new Float(0);
//		Float pushmy = (bsinfo != null && bsinfo.getHrPushmoney() != null) ? bsinfo
//				.getHrPushmoney() : new Float(0);
//		Float basepay = exealry - leavemy;
//		Float pay = basepay + pushmy;
		if ("1".equals(tcl.getHciType())) {//病假
			Map<String, Object> illmap = new HashMap<String, Object>();
			if(bsinfo.getHrLevel()!=null && bsinfo.getHrLevel().equalsIgnoreCase("12")){
				illmap = FormulaUtil.formulaById(24, exealry,tcl.getHciDaynum());// 病假算法
			}else{
				illmap = FormulaUtil.formulaById(18, exealry,tcl.getHciDaynum());// 病假算法
			}
			//按照天数进行计算结果算法	
			if (tcl.getHciDaynum() != null) {
				if (tcl.getHciDaynum() >= 1 && tcl.getHciDaynum() <= 7)
					totle = (Float) illmap.get("seven");
				else if (tcl.getHciDaynum() > 7 && tcl.getHciDaynum() <= 14)
					totle = (Float) illmap.get("fourteen");
				else
					totle = (Float) illmap.get("twoweeks");
			}
		} else if ("2".equals(tcl.getHciType())) {// 事假
			Map leavemap = FormulaUtil.formulaById(17, exealry, tcl.getHciDaynum());// 事假算法
			//试用期
			if(bsinfo.getHrLevel()!=null && bsinfo.getHrLevel().equalsIgnoreCase("12")){
				totle = (Float) leavemap.get("tryjob");
			}
			else{
				totle = (Float) leavemap.get("leavejob");
			}
		} else if ("3".equals(tcl.getHciType())) {// 违纪
			Map breakrule = FormulaUtil.formulaById(20, exealry, tcl.getHciDaynum());//违纪算法
			totle = (Float) breakrule.get("breakrule");
		} else if ("4".equals(tcl.getHciType())) {// 旷工
			Map absenteeism = FormulaUtil.formulaById(21, exealry, tcl.getHciDaynum());//旷工算法
			totle = (Float) absenteeism.get("absenteeism");
		} else if ("5".equals(tcl.getHciType())||"6".equals(tcl.getHciType())) {// 迟到 早退
			Map late = FormulaUtil.formulaById(22, tcl.getHciDaynum());//迟到 早退
			totle = (Float) late.get("late");
		} else if ("7".equals(tcl.getHciType())) {
			Map evectionmap = FormulaUtil.formulaById(19, exealry,tcl.getHciDaynum());// 异地补贴费用
			totle = (Float) evectionmap.get("evection");
		}
		return totle;
	}
	
	public TostHrCheckinlog queryChenckLog(TostHrCheckinlog chlog) throws Exception{
		return (TostHrCheckinlog) queryBychenck(chlog.getHrId(),chlog.getHciType(),chlog.getHciMonth());
	}
	
	
	public T queryBychenck(int hrId,String hciType,String month) throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("hrId", hrId);
		map.put("hciType", hciType);
		map.put("hciMonth", month);
		return getDao().queryBychenck(map);
	}
	public T queryBychencks(int hrId,String month) throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("hrId", hrId);
		map.put("hciMonth", month);
		return getDao().queryBychenck(map);
	}
	public List<T> queryCheByHrIdDerpart(TostHrCheckinlog tosthrcheckinlog,String derpart, String startM,String endM){
		return getDao().queryCheByHrIdDerpart(tosthrcheckinlog,derpart, startM, endM);
	}
}
